package com.zb.frame.modules.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zb.frame.modules.common.entity.UserToken;
import com.zb.frame.modules.common.mapper.UserTokenMapper;
import com.zb.frame.modules.common.service.UserTokenService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author bangZZ
 * @since 2020-06-05
 */
@Service
public class UserTokenServiceImpl extends ServiceImpl<UserTokenMapper, UserToken> implements UserTokenService {

    private static final Logger logger = LoggerFactory.getLogger(UserTokenServiceImpl.class);

    @Value("${zb.config.jwt.token.defaultExpired}")
    private int defaultExpired; // 默认accessToken的两倍时间

    @Autowired
    UserTokenMapper userTokenMapper;

    /**
     * 新增 refreshToken
     * @param userId 用户Id
     * @return refreshToken
     */
    @Override
    public String newUserToken(Long userId) {
        // 逻辑删除该用户所有的refresh_token
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.select("id");
        wrapper.eq("user_id", userId);
        List<UserToken> list = userTokenMapper.selectList(wrapper);
        if (list.size() > 0) {
            List<Long> idList = new ArrayList<>();
            for (UserToken item : list) {
                idList.add(item.getId());
            }
            userTokenMapper.deleteBatchIds(idList);
        }
        String refreshToken = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        UserToken userToken = new UserToken();
        userToken.setUserId(userId);
        userToken.setClientSecret(""); // 未使用
        userToken.setRefreshToken(refreshToken);
        userToken.setDelFlag(0);
        Date expired = new Date(System.currentTimeMillis() +  defaultExpired * 2 * 1000);
        userToken.setExpiredTime(expired);
        userTokenMapper.insert(userToken);
        return refreshToken;
    }

    /**
     * 根据refreshToken获取
     * @param token
     * @return UserToken
     */
    @Override
    public UserToken getUserTokenByToken(String token) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("refresh_token", token);
        return userTokenMapper.selectOne(wrapper);
    }

    @Override
    public void deleteById(Long id) {
        userTokenMapper.deleteById(id);
    }
}
